package com.sailing.xjpb.common.web;

import org.apache.commons.lang3.exception.ExceptionUtils;

/**
 * 返回结果工具类
 *
 * @author YaoWei 重构error代码逻辑
 */
public final class ResultUtils {

    private ResultUtils() {

    }

    /**
     * 定义成功返回
     *
     * @return 通用返回对象{@link ActionResult}
     */
    public static <T> ActionResult<T> success() {
        ActionResult<T> actionResult = new ActionResult<>();
        actionResult.setResponseCode(ResponseCode.SUCCESS.getCode());
        actionResult.setMessage(ResponseCode.SUCCESS.getMessage());
        return actionResult;
    }

    /**
     * 定义成功返回带对象
     *
     * @param result 返回值
     * @return 通用返回对象{@link ActionResult}
     */
    public static <T> ActionResult<T> success(T result) {
        return success(ResponseCode.SUCCESS.getMessage(), result);
    }

    /**
     * 定义成功返回带messge带对象
     *
     * @param message 返回消息
     * @param result  返回值
     * @return 通用返回对象{@link ActionResult}
     */
    public static <T> ActionResult<T> success(String message, T result) {
        ActionResult<T> actionResult = new ActionResult<>();
        actionResult.setResponseCode(ResponseCode.SUCCESS.getCode());
        actionResult.setMessage(message);
        actionResult.setResult(result);
        return actionResult;
    }

    /**
     * 系统异常
     */
    public static <T> ActionResult<T> errorOfSystem(int code, String message, String path) {
        ActionResult<T> actionResult = new ActionResult<>();
        actionResult.setMessage(message);
        actionResult.setException(message);
        actionResult.setPath(path);
        actionResult.setResponseCode(code);
        return actionResult;
    }

    /**
     * 业务异常
     */
    public static <T> ActionResult<T> errorOfBusiness(String message) {
        return errorOfSystem(ResponseCode.BUSINESS_ERROR.getCode(), message, null);
    }

    public static <T> ActionResult<T> error(ResponseCode responseCode, String message) {
        return errorOfSystem(responseCode.code(), message, message);
    }

    public static ActionResult<?> error(int errorCode, String message) {
        return errorOfSystem(errorCode, message, message);
    }

    public static <T> ActionResult<T> error(ResponseCode responseCode, String message, Throwable t) {
        String exception = ExceptionUtils.getMessage(t);
        return error(responseCode.getCode(), message, exception);
    }

    public static <T> ActionResult<T> error(int errorCode, String message, Throwable t) {
        String exception = ExceptionUtils.getMessage(t);
        return error(errorCode, message, exception);
    }

    public static <T> ActionResult<T> error(int errorCode, String message, String exceptionMsg) {
        ActionResult<T> actionResult = new ActionResult<>();
        actionResult.setMessage(message);
        actionResult.setResponseCode(errorCode);
        actionResult.setException(exceptionMsg);
        return actionResult;
    }

}
